﻿using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Threading;
using Avalonia;
using Avalonia.Media;
using Avalonia.Styling;
using Bee.Models.Menu;
using Bee.ViewModels.Menu;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Ke.Bee.Localization.Localizer.Abstractions;
using Microsoft.Extensions.Options;

namespace Bee.ViewModels;

public partial class MainWindowViewModel : ViewModelBase
{
    /// <summary>
    /// 工具栏按钮集合
    /// </summary>
    [ObservableProperty] private ObservableCollection<MenuItemViewModel> _toolbarMenus;

    /// <summary>
    /// 设置菜单集合
    /// </summary>
    [ObservableProperty] private ObservableCollection<MenuItemViewModel> _settingMenus;

    /// <summary>
    /// 本地化资源
    /// </summary>
    private ILocalizer _l;
    /// <summary>
    /// 菜单选项
    /// </summary>
    private MenuItem[] _menuItems;

    public MainWindowViewModel(IOptions<MenuItem[]> menuItems, ILocalizer localizer)
    {
        _l = localizer;
        _menuItems = menuItems.Value;
        LoadMenus();
    }

    /// <summary>
    /// 加载菜单
    /// </summary>
    void LoadMenus()
    {
        var toolbarMenus = _menuItems.Where(a => a.Group == "Toolbar").Select(MenuItemToViewModel);
        var settingMenus = _menuItems.Where(a => a.Group == "Settings").Select(MenuItemToViewModel);
        ToolbarMenus = [..toolbarMenus];
        SettingMenus = [..settingMenus];
    }

    /// <summary>
    /// 将菜单转化为viewmodel
    /// </summary>
    Func<MenuItem, MenuItemViewModel> MenuItemToViewModel => a => new MenuItemViewModel(_l[a.LocaleKey])
    {
        Key = a.Key,
        IsActive = a.IsActive == true,
        Icon = string.IsNullOrEmpty(a.Icon) ? null : StreamGeometry.Parse(a.Icon),
        CommandParameter = a.CommandParameter,
        CommandType = a.CommandType,
        Items = a.Items?.Select(MenuItemToViewModel).ToList() ?? [],
        MenuClickCommand =
            GetRelayCommand(a.CommandType) ??
            new RelayCommand<MenuItemViewModel>(menuItem => { }) // 返回结果为空时，创建无任何操作的中继命令，否则按将不可用
    };

    /// <summary>
    /// 根据命令类型返回中继命令
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    IRelayCommand? GetRelayCommand(string? type)
    {
        if (!Enum.TryParse<MenuClickCommandType>(type, out var cmdType)) return null;
        return cmdType switch
        {
            // 激活菜单命令返回的中继命令
            MenuClickCommandType.Active => new RelayCommand<MenuItemViewModel>(menuItem =>
            {
                if (menuItem == null || menuItem.IsActive) return;
                var menu = ToolbarMenus.FirstOrDefault(model => model.IsActive);
                if (menu != null) menu.IsActive = false;
                menuItem!.IsActive = true;
            }),
            // 主题切换返回的中继命令
            MenuClickCommandType.SwitchTheme => new RelayCommand<MenuItemViewModel>(menuItem =>
            {
                if (Application.Current is null) return;
                var tv = menuItem?.CommandParameter switch
                {
                    nameof(ThemeVariant.Default) => ThemeVariant.Light,
                    nameof(ThemeVariant.Dark) => ThemeVariant.Dark,
                    _ => ThemeVariant.Light
                };
                Application.Current.RequestedThemeVariant = tv;
                // Application.Current.RequestedThemeVariant = Application.Current.RequestedThemeVariant == ThemeVariant.Light
                //     ? ThemeVariant.Dark
                //     : ThemeVariant.Light;
            }),

            // 使用默认浏览器打开网页
            MenuClickCommandType.Link => new RelayCommand<MenuItemViewModel>(menuItem =>
            {
                var url = menuItem?.CommandParameter;
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = url,
                    UseShellExecute = true
                });
            }),
            // 语言切换中继命令
            MenuClickCommandType.SwitchLanguage => new RelayCommand<MenuItemViewModel>(menuItem =>
            {
                var language = menuItem?.CommandParameter;
                _l.CurrentCulture = _l.AvailableCultures.FirstOrDefault(a => a.IetfLanguageTag == language) ?? Thread.CurrentThread.CurrentCulture;
                LoadMenus();
            }),
            _ => null
        };
    }
}